<template>
  <div class="user-blacklist-form-page">
    <el-card>
      <div class="form-header">
        <h2>{{ formTitle }}</h2>
        <el-button type="primary" @click="goBack">返回列表</el-button>
      </div>

      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
        class="form-content"
      >
        <el-form-item label="用户ID" prop="value">
          <el-input
            v-model="formData.value"
            placeholder="请输入用户ID"
            maxlength="50"
          />
        </el-form-item>

        <el-form-item label="原因" prop="reason">
          <el-input
            v-model="formData.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入加入黑名单的原因"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, computed } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
  import { saveRiskBlack, updateRiskBlack, getRiskBlackDetail } from '@/api/riskApi'
  import type {
    RiskBlackSaveParam,
    RiskBlackUpdateParam,
    RiskBlack
  } from '@/api/model/riskModel'
  import { ApiStatus } from '@/utils/http/status'

  const route = useRoute()
  const router = useRouter()

  const formRef = ref<FormInstance>()
  const loading = ref(false)
  const isEdit = ref(false)
  const blackId = ref<number>(0)

  const formData = ref<RiskBlackSaveParam | RiskBlackUpdateParam>({
    type: 2, // 用户黑名单类型
    value: '',
    reason: ''
  })

  const formRules = reactive<FormRules>({
    value: [
      { required: true, message: '请输入用户ID', trigger: 'blur' },
      { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    reason: [
      { required: true, message: '请输入原因', trigger: 'blur' },
      { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
    ]
  })

  const formTitle = computed(() => {
    return isEdit.value ? '编辑用户黑名单' : '新增用户黑名单'
  })

  onMounted(() => {
    initForm()
  })

  function initForm() {
    const { id } = route.params
    if (id && typeof id === 'string') {
      isEdit.value = true
      blackId.value = parseInt(id)
      loadBlackDetail(blackId.value)
    } else {
      isEdit.value = false
      resetForm()
    }
  }

  // 加载黑名单详情
  async function loadBlackDetail(id: number) {
    try {
      loading.value = true
      const res = await getRiskBlackDetail({ riskBlackId: id })
      if (res.code === ApiStatus.success && res.data) {
        const detail = res.data
        formData.value = {
          type: detail.type || 2,
          value: detail.value || '',
          reason: detail.reason || ''
        }
        if (isEdit.value) {
          (formData.value as RiskBlackUpdateParam).riskBlackId = detail.riskBlackId
        }
      } else {
        ElMessage.error('获取黑名单详情失败')
        goBack()
      }
    } catch (error) {
      console.error('获取黑名单详情失败:', error)
      ElMessage.error('获取黑名单详情失败')
      goBack()
    } finally {
      loading.value = false
    }
  }

  // 提交表单
  async function submitForm() {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      loading.value = true

      if (isEdit.value) {
        const updateParam: RiskBlackUpdateParam = {
          riskBlackId: blackId.value,
          type: 2,
          value: formData.value.value!,
          reason: formData.value.reason
        }
        const res = await updateRiskBlack(updateParam)
        if (res.code === ApiStatus.success) {
          ElMessage.success('更新成功')
          goBack()
        } else {
          ElMessage.error(res.message || '更新失败')
        }
      } else {
        const saveParam: RiskBlackSaveParam = {
          type: 2,
          value: formData.value.value!,
          reason: formData.value.reason
        }
        const res = await saveRiskBlack(saveParam)
        if (res.code === ApiStatus.success) {
          ElMessage.success('新增成功')
          goBack()
        } else {
          ElMessage.error(res.message || '新增失败')
        }
      }
    } catch (error) {
      console.error('提交表单失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 重置表单
  function resetForm() {
    if (formRef.value) {
      formRef.value.resetFields()
      formData.value = {
        type: 2,
        value: '',
        reason: ''
      }
    }
  }

  // 返回列表
  function goBack() {
    router.push('/risk/userBlackList')
  }
</script>

<style lang="scss" scoped>
  .user-blacklist-form-page {
    padding: 20px;

    .form-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30px;
      padding-bottom: 15px;
      border-bottom: 1px solid var(--art-border-color-light);

      h2 {
        margin: 0;
        color: var(--art-text-color-primary);
        font-size: 20px;
        font-weight: 500;
      }
    }

    .form-content {
      max-width: 600px;
      margin: 0 auto;

      .el-form-item {
        margin-bottom: 22px;
      }

      .el-input,
      .el-textarea {
        width: 100%;
      }
    }

    // 响应式设计
    @media screen and (max-width: $device-phone) {
      padding: 10px;

      .form-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;

        h2 {
          font-size: 18px;
        }
      }

      .form-content {
        .el-form-item {
          :deep(.el-form-item__label) {
            width: 100% !important;
            text-align: left;
          }

          :deep(.el-form-item__content) {
            margin-left: 0 !important;
          }
        }
      }
    }
  }
</style>